$( document ).ready(function() {
	$("#messageDiv").empty();
	$("#messageDiv").hide();
	$("[name='searchUserId']").val("");
	$("[name='searchFirstname']").val("");
	$("[name='searchLastname']").val("");
});

function getUserSearchResult() {
	$("#userResult").empty();
	$("#messageDiv").empty();
	$("#messageDiv").hide();
	$.getJSON("admin/searchResult.html?searchUserId="+$("[name='searchUserId']").val()+"&searchFirstname="+$("[name='searchFirstname']").val()+"&searchLastname="+$("[name='searchLastname']").val(), function(data) {
		if(!jQuery.isEmptyObject(data.userSearchResult)){
			$("#userResult").data("userSearchResult", data);
			printTableBody(data.userSearchResult);
		}else{
			$("#userResult").append("<strong>No result.</strong>");
		}
	});
}

function printTableBody(userSearchResult){
	$("#userResult")
	.append(
			"<table id=\"list\" class=\"tablecss\">" +
			"<thead>" +
			"<tr>" +
			"<th>User id</th>" +
			"<th>First name</th>" +
			"<th>Last name</th>" +
			"<th>Gender</th>" +
			"<th></th>"+
			"</tr>" +
			"</thead>" +
			"<tbody id=\"tableBody\">" +
			"</tbody>" +
			"</table>");
var tr;

		$(userSearchResult).each(function (i,v){
			tr = $("<tr>");
			tr.append("<td>" + v.userId + "</td>");
			tr.append("<td>" + v.firstname + "</td>");
			tr.append("<td>" + v.lastname + "</td>");
			var gen=v.gender;
			if(gen=='m'){
				tr.append("<td>male</td>");
			}else if(gen=='f'){
				tr.append("<td>female</td>");
			}else{
				tr.append("<td></td>");
			}
			tr.append("<td><button class=\"button\" onclick=\"resetPwd("+v.userId+","+v.role+")\">reset</button></td>");
			tr.append("</tr>");
			$("#tableBody").append(tr);
		});
$("#list").tablesorter({
	widgets : [ 'zebra' ],
	headers : {
		4 : {
			sorter : false
		}
	}
});
}

function resetPwd(userId,role){
	$.getJSON("admin/resetPassword.html?resetUserId="+userId+"&resetRole="+role,function(data){
		if(data.flag==true){
			$("#messageDiv").removeClass("success");
			$("#messageDiv").removeClass("error");
			$("#messageDiv").addClass("success");
			$("#messageDiv").html("<strong>"+data.message+"</strong>");
			$("#messageDiv").show();
		}else if(data.flag==false){
			$("#messageDiv").removeClass("success");
			$("#messageDiv").removeClass("error");
			$("#messageDiv").addClass("error");
			$("#messageDiv").html("<strong>"+data.message+"</strong>");
			$("#messageDiv").show();
		}
		
	});
}